<template>
    <el-card class="h-32">
        <el-form>
            <el-form-item label="职位搜索" class="float-left">
                <el-input placeholder="请你输入搜索职位的关键字" class="w-80" v-model="jobs"></el-input>
            </el-form-item>
            <el-form-item class="float-right">
                <el-button type="primary" @click="search" :disabled="jobs ? false : true">搜索</el-button>
                <el-button @click="reset">重置</el-button>
            </el-form-item>
        </el-form>
    </el-card>

    <el-card class="mt-3">
        <el-button type="primary" icon="Plus" @click="addJobs">添加职位</el-button>
        <el-table border class="mt-3" :data="allRole">
            <el-table-column label="#" type="index" width="50" align="center"></el-table-column>
            <el-table-column align="center" property="id" label="ID"></el-table-column>
            <el-table-column align="center" property="roleName" label="职位名称"></el-table-column>
            <el-table-column align="center" property="createTime" label="创建时间"></el-table-column>
            <el-table-column align="center" property="updateTime" label="更新时间"></el-table-column>
            <el-table-column align="center" label="操作">
                <template #="{ row }">
                    <el-button type="primary" size="small" @click="setRole(row)" icon="UserFilled"> 分配权限</el-button>
                    <el-button type="primary" size="small" @click="edit(row)" icon="Edit"> 编辑</el-button>
                    <el-popconfirm width="220" confirm-button-text="确定" cancel-button-text="取消" icon="Delete"
                        icon-color="#F56C6C" :title="`确定要删除角色${row.roleName}吗?`" @confirm="remove(row)">
                        <template #reference>
                            <el-button type="primary" size="small" icon="Delete">删除</el-button>
                        </template>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>

        <el-pagination class="mt-3" v-model:current-page="pageNo" v-model:page-size="pageSize"
            :page-sizes="[10, 20, 30, 40]" :background="true" layout="prev, pager, next, jumper,->,sizes,total"
            :total="total" @size-change="handleSizeChange" @current-change="getAllRole" />
    </el-card>

    <!-- 新增和更新的弹窗 -->
    <el-dialog v-model="dialogVisible" :title="paramsRole.id ? '更新角色' : '添加角色'" width="50%">
        <el-form :model="paramsRole" ref="ruleFormRef" :rules="rules">
            <el-form-item label="职位名称" prop="roleName">
                <el-input placeholder="请你输入职位的名称" v-model="paramsRole.roleName"></el-input>
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="save">
                    确认
                </el-button>
            </span>
        </template>
    </el-dialog>
    <!-- 分配角色权限的抽屉 -->
    <el-drawer v-model="drawer">
        <template #header>
            <h1>分配角色权限</h1>
        </template>
        <template #default>
            <el-tree ref="tree" :data="menuArr" show-checkbox node-key="id" default-expand-all :default-checked-keys="selectArr"
                :props="defaultProps" />
        </template>
        <template #footer>
            <div style="flex: auto">
                <el-button @click="drawer.value = false">取消</el-button>
                <el-button type="primary" @click="confirmClick">确定</el-button>
            </div>
        </template>
    </el-drawer>
</template>

<script setup lang="ts">
import { ElMessage } from 'element-plus'
import { ref, onMounted, reactive, nextTick } from 'vue'
import { reqAllRoles, reqDeleteRoles, reqAddOrUpdateRole, reqAllotRole ,reqSetPermisstion} from "../../../api/acl/role/index"

//搜索职位的值
const jobs = ref<any>('')
//分页器当前页
const pageNo = ref<any>(1)
//分页器每页的数据
const pageSize = ref<any>(10)
//分页器的全部数据=条数
const total = ref<any>()
//全部的数据
const allRole = ref<any>()

//获取form组件的实例对象
const ruleFormRef = ref<any>()
//新增和更新的模态框的值
const dialogVisible = ref<boolean>(false)
// 收集角色信息的响应式数据
const paramsRole = reactive<any>({
    roleName: ''
})

//抽屉的显示与隐藏
const drawer = ref<any>(false)
//抽屉中的角色分配数据'
const defaultProps = {
    children: 'children',
    label: 'name',
}
let menuArr = ref<any>([]);
//需要勾选树形控件的id数据
let selectArr= ref<any>([]);
//获取tree组件的实例
let tree=ref<any>()

// 钩子函数进入页面立即执行
onMounted(() => {
    getAllRole()
})
const getAllRole = async (pager = 1) => {
    pageNo.value = pager
    let result: any = await reqAllRoles(pageNo.value, pageSize.value, jobs.value)
    if (result.code == 200) {
        allRole.value = result.data.records
        total.value = result.data.total
    }
}
//每页展示的条数 的回调 进行重新调用接口请求数据渲染
const handleSizeChange = () => {
    getAllRole()
}
//自定义校验规则
const roleJobs = (rule: any, value: any, callback: any) => {
    console.log(rule);
    
    if (value.trim().length >= 2) {
        callback()
    } else {
        callback(new Error('请输入检查内容然后再操作!'))
    }
}
const rules = {
    roleName: [
        { required: true, trigger: 'blur', validator: roleJobs },
    ],

}

//添加角色按钮的回调
const addJobs = () => {
    dialogVisible.value = true
    Object.assign(paramsRole, {
        id: 0,
        roleName: ''
    })
    nextTick(() => {
        ruleFormRef.value.clearValidate('roleName');
    });
}

// 确定按钮的回调
const save = async () => {
    //点击保存按钮的时候,务必需要保证表单全部复合条件在去发请求

    await ruleFormRef.value.validate()
    let result: any = await reqAddOrUpdateRole(paramsRole)
    console.log(result);
    if (result.code == 200) {
        dialogVisible.value = false

        ElMessage({
            showClose: true,
            message: paramsRole.id ? '修改成功!' : '添加成功!',
            type: 'success',
        })
        window.location.reload();
        getAllRole()
    } else {
        dialogVisible.value = false

        ElMessage({
            showClose: true,
            message: paramsRole.id ? '修改失败!' : '修改成功!',
            type: 'info',
        })

    }
    Object.assign(paramsRole, {
        roleName: ''
    })

}
//编辑按钮的回调
const edit = async (row: any) => {
    dialogVisible.value = true
    Object.assign(paramsRole, row)
    nextTick(() => {
        ruleFormRef.value.clearValidate('roleName');
    });
}

//分配角色权限按钮的回调
const setRole = async (row: any) => {
    drawer.value = true
    Object.assign(paramsRole, row);
    let result: any = await reqAllotRole(paramsRole.id)
    if (result.code == 200) {
        menuArr = result.data
        selectArr.value=  filterSelectArr(menuArr,[])
    }
}

const filterSelectArr=(a:any,b:any)=>{
    a.forEach((item:any) => {
        if (item.select&&item.level == 4) {
         b.push(item.id)
        }
        if (item.children && item.children.length>0) {
            filterSelectArr(item.children,b)
         }
    });
    return b
}

//分配角色权限的确定按钮的回调
const confirmClick =async () => {
    let reloId=paramsRole.id
    let Arr=tree.value.getCheckedKeys()
    let Arr1=tree.value.getHalfCheckedKeys()
  let  paramsId= Arr.concat(Arr1)
  let result:any=await  reqSetPermisstion (reloId,paramsId)
  if (result.code==200) {
    drawer.value = false

    ElMessage({
            showClose: true,
            message: '分配成功!',
            type: 'success',
        })
    getAllRole()

    
  }else{
    drawer.value = false
    ElMessage({
            showClose: true,
            message: '分配失败!',
            type: 'info',
        })
  }
}




//删除按钮的回调
const remove = async (row: any) => {

    let result: any = await reqDeleteRoles(row.id)
    console.log(result);

    if (result.code == 200) {
        ElMessage({
            showClose: true,
            message: '删除成功!',
            type: 'success',
        })
        getAllRole()
    } else {
        ElMessage({
            showClose: true,
            message: '删除失败!',
            type: 'info',
        })
    }
}
//搜索按钮的回调
const search = () => {
    getAllRole()
    jobs.value = ''
}
//重置按钮的回调
const reset = () => {
    jobs.value = ''
    getAllRole()

}
</script>

<style lang="scss" scoped></style>